<?php
require_once("inc.member.php");

$this_title="$vars[member_title] &raquo; ".__("Purchase History");
$content_title = $page_title=__("Purchase History");

require_once("inc.sales_tab.php");

$add_edit_file=$vars["file"]["member"]["add_edit_sales"];

$item_per_page=$vars["user_item_per_page"];

$r_sale_point = $vars['dbv']['sale_point'];

$search_options["status"]["option"] = $r_status=array("confirmed","cancelled");
$search_options["status"]["option_display"] = $r_status_d=array("confirmed"=>__("Confirmed"),"cancelled"=>__("Cancelled"));
$search_options["status"]["display"] = __("Status");
//$search_options["first_sale"]["option"] = $r_first_sale=array("y","n");
//$search_options["first_sale"]["option_display"] = $r_first_sale_d=array("y"=>__("Yes"),"n"=>__("No"));
//$search_options["first_sale"]["display"] = __("Plan A");
$search_options["payment_type"]["option"] = $r_payment_channel=$vars['dbv']['sale_payment'];
$search_options["payment_type"]["option_display"] = $r_payment_channel_d=$vars['dbv']['sale_payment_d'];
$search_options["payment_type"]["display"] = __("Payment Channel");
$search_options["collected"]["option"] = $r_collected_type = array("y","n");
$search_options["collected"]["option_display"] = $r_collected_type_d = array("y"=>__("Collected"),"n"=>__("Uncollected"));
$search_options["collected"]["display"] = __("Products Collected");

//#####SEARCH#####
if($_GET["s"]){
	$searching=1;
	$search_query=msales_search($_GET);
}
if($get_s['v']){
	$hidden_inputfields = "<input type='hidden' name='v' value='$get_h[v]' />";
}

//textbox search, prefix "_sp_", "uid"=>__("Member ID")
$r_textsearch=array("uid"=>__("Member ID"));

//custom search fields
$fromdate_search=generate_dmy_input("_sdf", $get_s["_sdf_day"], $get_s["_sdf_month"], $get_s["_sdf_year"], "class='inputbox'", 2009);
$todate_search=generate_dmy_input("_sdt", $get_s["_sdt_day"], $get_s["_sdt_month"], $get_s["_sdt_year"], "class='inputbox'", 2009);
$custom_date['title']=__("Date");
$custom_date['value']=__("From")." ".$fromdate_search."<br />".__("To")." ".$todate_search;

$searchfields_ordering=array("uid",$custom_date);
$search_ui=build_admin_search_ui($searching, $this_file, $search_options, $r_textsearch, $searchfields_ordering, $inputbox_style, $hidden_inputfields);
//#####END SEARCH#####

//#####LIST MEMBER SALES#####
if($searching){
	$count_sql=$search_query["count_sql"];
	$record_sql=$search_query["record_sql"];
	foreach($r_sale_point as $point_type){
		$point_sql[$point_type] = $search_query[$point_type."_sql"];
	}
}else{
	$cid_uid_q = $get_s['v'] == 'u'? "s.creator='u' and s.cid='$uid' and s.uid!='$uid'" : "s.uid='$uid'";
	$count_sql="select count(s.*) from $db->purchase s inner join $db->users u on u.id=s.uid where $cid_uid_q";
	foreach($r_sale_point as $point_type){
		$point_sql[$point_type] = "select sum(total_$point_type) from $db->purchase s where $cid_uid_q";
	}
	$record_sql="select u.code, s.* from $db->purchase s inner join $db->users u on u.id=s.uid where $cid_uid_q order by cdate desc limit <%limit_start%>, <%limit%>";
}

$cur_page=$_GET["nav"];
$total_record=@mysql_result(mysql_query($count_sql), 0);
$total_page=ceil($total_record/$item_per_page);
$page=($cur_page? ($cur_page>$total_page? $total_page : ($cur_page<1? 1 : $cur_page)) : 1);
$limit_start=($page-1)*$item_per_page;
$nav_link=format_page($page, $total_page, 20);
$this_page_total=@mysql_num_rows($r=mysql_query(str_replace("<%limit_start%>", $limit_start, str_replace("<%limit%>", $item_per_page, $record_sql))));
$k=0;
foreach($r_sale_point as $point_type){
	$total_point[$point_type]=@mysql_result(mysql_query($point_sql[$point_type]), 0) or 0;
	$point_list.=" ".replace_tag(__("Total <%title%>: <%x%>."), array("<%title%>"=>__(strtoupper($point_type)), "<%x%>"=>number_format($total_point[$point_type], 2)));
}
for($i=0;$i<$this_page_total;$i++){
	$run_no = (($page - 1) * $item_per_page) + $i + 1;
	$sale=mysql_fetch_assoc($r);	/*	switch($sale['total_bv']){		case "1000.00":			$total_bv = 1000;			break;		case "3000.00":			$total_bv = 3150;			break;		case "7000.00":			$total_bv = 7700;			break;		case "15000.00":			$total_bv = 17250;			break;		case "30000.00":			$total_bv = 36000;			break;		case "90000.00":			$total_bv = 112500;			break;		default:			$total_bv = $sale['total_bv'];	}	*/	if($sale['total_bv']>=1000 and $sale['total_bv']<3000){		$total_bv = $sale['total_bv'];	}elseif($sale['total_bv']>=3000 and $sale['total_bv']<7000){		$total_bv = $sale['total_bv'] * 1.05;	}elseif($sale['total_bv']>=7000 and $sale['total_bv']<15000){		$total_bv = $sale['total_bv'] * 1.1;	}elseif($sale['total_bv']>=15000 and $sale['total_bv']<30000){		$total_bv = $sale['total_bv'] * 1.15;	}elseif($sale['total_bv']>=30000 and $sale['total_bv']<90000){		$total_bv = $sale['total_bv'] * 1.2;	}elseif($sale['total_bv']>=90000){		$total_bv = $sale['total_bv'] * 1.25;	}		if($sale['uid']==870){		$total_bv = $sale['total_bv'] * 1.05;	}elseif($sale['uid']==218 || $sale['uid']==1322 || $sale['uid']==1853 || $sale['uid']==2237 || $sale['uid']==2431){		$total_bv = $sale['total_bv'] * 1.15;	}elseif($sale['uid']==1560){		$total_bv = $sale['total_bv'] * 1.10;	}elseif($sale['uid']==1557 || $sale['uid']==1830){		$total_bv = $sale['total_bv'] * 1.20;		$percentage = '120%';	}
	$sale_row.="
	<tr class='row$k".($sale['status']=='cancelled'? " cancelled" : "")."'>		<td>".date($vars["date_format_short"], strtotime($sale["cdate"]))."</td>
		<td><a href='$add_edit_file?type=edit&id=$sale[id]'>".__('View')."</a></td>
		<td>$sale[code]</td>
		<td>".number_format($sale['total_bv'], 2)."</td>
		<td>".$r_payment_channel_d[$sale["payment_type"]]."</td>
		<td".($sale['status']=='cancelled'? " style='color:red; font-weight:bold;'" : "").">".$r_status_d[$sale["status"]]."</td>
	</tr>";
	$k=1-$k;
}

//listing text
$listing_text="";
//listing
$sales_list=($errmsg || $msg? $errmsg.$msg : "").'<div class="panel panel-sky">                        <div class="panel-heading">                            <h4>'.$content_title.'</h4>                            <div class="options">                                   <a href="javascript:;"><i class="fa fa-cog"></i></a>                                <a href="javascript:;"><i class="fa fa-wrench"></i></a>                                <a href="javascript:;" class="panel-collapse"><i class="fa fa-chevron-down"></i></a>                            </div>                        </div>                        <div class="panel-body collapse in">                            <table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered datatables" id="example">                                <thead>                                    <tr>                                        <th>'.__("Sales Date").'</th>                                        <th>'.__("Actions").'</th>                                        <th>'.__("Member ID").'</th>                                        <th>'.replace_tag(__("Total <%title%>"), array("<%title%>"=>__("Amount"))).'</th>                                        <th>'.__("Status").'</th>                                    </tr>                                </thead>                                <tbody>                                    '.$sale_row.'                                </tbody>                            </table>                        </div>                    </div>';

//#####END MEMBER SALES LIST#####

$content=$sales_list;
//$content=str_replace("<%tab_content%>", $content, $tab);

print format_member_page($content, $this_title, $content_title, $css);

function msales_search($in_get){
	global $vars, $uid, $r_sale_point, $search_options;
	$db=$vars["db"];

	$get=$in_get;
	$search_type="and";
	$r_like_search=array("refno");
	//format search string
	foreach($get as $field=>$value){
		$value=trim($value);
		//search checkbox option
		if(preg_match('/^_so_/', $field)){
			preg_match('/(?<=_so_).+(?=__)/', $field, $matchf);
			$f=$matchf[0];
			preg_match('/(?<=__).+$/', $field, $matchv);
			$v=$matchv[0];
			$r_searchquery[$f].=($r_searchquery[$f]? "," : "")."'$v'";
		}
		//db field name search
		if(substr($field, 0, strlen("_sp_"))=="_sp_"){
			if($field != '_sp_prefno'){
				if(strlen($value)){
					$db_fieldname=substr($field, strlen("_sp_"));
					$db_fieldname_q.=($db_fieldname_q? " and " : "")."(".(in_array($db_fieldname, $r_like_search)? format_search_field_like("s.".$db_fieldname, $value) : format_search_field("s.".$db_fieldname, $value)).")";
				}
			}
		}
	}
	if(isset($r_searchquery)){
		foreach($r_searchquery as $field => $query){
			$option_q.=($option_q? " and " : "")."s.$field in ($query)";
		}
	}else{
		$option_q="1=1";
	}
	if(strlen($get['_sp_prefno'])){
		$prod_str = format_search_field_like("refno", $get['_sp_prefno']);
		$prod_q = "s.id in (select distinct slid from $db->purchase_detail where $prod_str)";
	}else{
		$prod_q = "1=1";
	}
	$db_fieldname_q=$db_fieldname_q? $db_fieldname_q : "1=1";
	if(strlen($get['_sdf_day']) || strlen($get['_sdf_month']) || strlen($get['_sdf_year'])){
		if(!strlen($get['_sdf_day']) || !strlen($get['_sdf_month']) || !strlen($get['_sdf_year'])){
			$date_q="1=2";
		}else{
			$fdate="$get[_sdf_year]-".pad_length($get["_sdf_month"], 2)."-".pad_length($get["_sdf_day"], 2);
			if(!@checkdate($get['_sdf_month'], $get['_sdf_day'], $get['_sdf_year'])){
				$date_q="1=2";
			}else{
				if(strlen($get['_sdt_day']) || strlen($get['_sdt_month']) || strlen($get['_sdt_year'])){
					if(!strlen($get['_sdt_day']) || !strlen($get['_sdt_month']) || !strlen($get['_sdt_year'])){
						$date_q="1=2";
					}else{
						$tdate="$get[_sdt_year]-".pad_length($get["_sdt_month"], 2)."-".pad_length($get["_sdt_day"], 2);
						if(!@checkdate($get['_sdt_month'], $get['_sdt_day'], $get['_sdt_year'])){
							$date_q="1=2";
						}else{
							$date_q="s.cdate>='$fdate 00:00:00' and s.cdate<='$tdate 23:59:59'";
						}
					}
				}else{
					$date_q="s.cdate>='$fdate 00:00:00' and s.cdate<='$fdate 23:59:59'";
				}
			}
		}
	}else{
		$date_q="1=1";
	}

	if($get['v'] == 'u'){
		$cid_uid_q = "s.creator='u' and s.cid='$uid' and s.uid!='$uid'";
	}else{
		$cid_uid_q = "s.uid='$uid'";
	}
	
	$count_sql="select count(s.*) from $db->purchase s inner join $db->users u on u.id=s.uid where $cid_uid_q and $prod_q and $option_q and $db_fieldname_q and $date_q";
	$record_sql="select u.code, s.* from $db->purchase s inner join $db->users u on u.id=s.uid where $cid_uid_q and $prod_q and $option_q and $db_fieldname_q and $date_q order by id limit <%limit_start%>, <%limit%>";
	foreach($r_sale_point as $point_type){
		$return_sql[$point_type."_sql"] = "select sum(total_$point_type) from $db->purchase s where $cid_uid_q and $prod_q and $option_q and $db_fieldname_q and $date_q";
	}
	
	$return_sql['count_sql'] = $count_sql;
	$return_sql['record_sql'] = $record_sql;

	return $return_sql;
}
?>